package nku.csc660;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server extends Thread
{
	ServerSocket MyService = null;

    public Server()throws IOException
    {
    	try
    	{
			MyService = new ServerSocket(9999);
		}
    	catch (IOException e)
		{
			System.out.println("Couldn't start the server socekt!");
			throw new IOException("Couldn't start the Server Socekt, Connection!");
		}
    }

    public Socket waitForConnection()throws IOException
    {
    	Socket serviceSocket = null;
    	try
    	{
			serviceSocket = MyService.accept();
			System.out.println("I have recieved a connection! ");
			return serviceSocket;
		}
		catch(IOException e)
		{
			System.out.println(e);
			System.out.println("Recieving a connection failed! ");
			throw new IOException("Couldn't connect to Client, Connection Failed!");
		}
    }

    public static BufferedReader openInputStream(Socket socket)throws IOException
    {
    	try
    	{
			DataInputStream inputStream = new DataInputStream(socket.getInputStream());
			BufferedReader input = new BufferedReader(new InputStreamReader(inputStream));
			System.out.println("The input stream is opened to recieve messages from Client!");
			return input;
		}
		catch(IOException e)
		{
			System.out.println(e);
			System.out.println("Failed to open an input stream to recieve messages from Client!");
			throw new IOException("Failed to open an input stream to recieve messages from Client!");
		}
    }

    public static PrintWriter openOutputStream(Socket socket)throws IOException
    {
		try
		{
			PrintWriter output = new PrintWriter(socket.getOutputStream());
			System.out.println("The output stream is opened to send messages to Client!");
			return output;
		}
		catch(IOException e)
		{
			System.out.println(e);
			System.out.println("Failed to open stream to send messages to Client!");
			throw new IOException("Failed to open stream to send messages to Client!");
		}
    }

    public static void sendMessage1(PrintWriter output, String... lines)
    {
    	if(lines!= null){
	    	for(String line: lines)
	    	{
	    		if(line != null){
	    			output.println(line);
	    		}
	    	}
	    	output.flush();
    	}
    }

    public static String readLine(BufferedReader input)throws IOException
    {
    	String line = null;
    	try
    	{
    		line = input.readLine();
		}
		catch(IOException e)
		{
			System.out.println(e);
			System.out.println("Communication Failed!");
			throw new IOException("Couldn't readLine from the Client!");
		}
		return line;
    }

	public static void sendMessage(PrintWriter output, String clientName, String... lines) {
		output.print(clientName + ": ");
		sendMessage1(output, lines);
	}
}
